/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package argentracker.activeentity.metadata;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import argentracker.activeentity.ActiveEntity;
import argentracker.activeentity.exceptions.ActiveEntityException;

/**
 * briefly description.
 * 
 * extense description.
 * 
 * @author matero (matero _at_ gmail _dot_ com)
 */
public class ConcreteActiveEntityMetadata<AE extends ActiveEntity<AE>> extends ActiveEntityMetadata<AE> {
    private final Constructor<AE> defaultConstructor;

    protected ConcreteActiveEntityMetadata(Class<AE> activeEntityClass) {
        super(activeEntityClass);
        this.defaultConstructor = getDefaultConstructorFor(activeEntityClass);
    }

    private Constructor<AE> getDefaultConstructorFor(Class<AE> activeEntityClass) {
        try {
            return activeEntityClass.getConstructor();
        } catch (SecurityException e) {
            throw new ActiveEntityException("Default constructor could not be used on Active Entity Class ["
                    + activeEntityClass + "].", e);
        } catch (NoSuchMethodException e) {
            throw new ActiveEntityException("Default constructor not found on Active Entity Class ["
                    + activeEntityClass + "].", e);
        }
    }

    @Override
    public boolean isAbstract() {
        return false;
    }

    @Override
    public AE newActiveEntity() {
        try {
            return this.defaultConstructor.newInstance();
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException("unexpected exception of class IllegalArgumentException", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException("unexpected exception of class InstantiationException", e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("unexpected exception of class IllegalAccessException", e);
        } catch (InvocationTargetException e) {
            throw new IllegalStateException("unexpected exception of class InvocationTargetException", e);
        }
    }

}
